/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessions;

import entities.Album;
import entities.Artist;
import java.util.Date;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import webservices.MusicWebServices;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@Stateless
@LocalBean
public class AlbumManager {

    @PersistenceContext(unitName = "ProjetStreamingBoulinguezCheng-ejbPU")
    private EntityManager em;

    // Create an album if this album doesn't exist yet - each album of an artist have a unique title
    public Album createAlbum(String title, Artist artist, Date releaseDate) {
        // Get an eventual existing album
        Album existingAlbum = getAlbum(title, artist);

        // if it doesn't exist, create it
        if (existingAlbum == null) {
            String relativePathArt = MusicWebServices.getCoverArt(title);
            Album album = new Album(relativePathArt, title, artist, releaseDate);
            persist(album);

            return album;
        }

        return existingAlbum;
    }
    
    // Get an album with it id
    public Album getAlbum(Long id) {
        Query query = em.createNamedQuery("Album.getById");
        query.setParameter("id", id);

        try {
            Object result = query.getSingleResult();
            return (Album) result;
        } catch (NoResultException e) {
            return null;
        }
    }
    
    // Get an album with it title and artist
    public Album getAlbum(String albumTitle, Artist artist) {
        Query query = em.createNamedQuery("Album.getByTitleAndArtist");
        query.setParameter("title", albumTitle);
        query.setParameter("artist", artist);

        try {
            Object result = query.getSingleResult();
            return (Album) result;
        } catch (NoResultException e) {
            return null;
        }
    }

    // Get all albums
    public List<Album> getAllAlbums() {
        Query query = em.createNamedQuery("Album.findAll");
        return query.getResultList();
    }
    
    public void incAlbumPlayCount(Long albumId) {
        Album album = getAlbum(albumId);
        album.incPlayCount();
        update(album);
    }
    
    public void persist(Object object) {
        em.persist(object);
    }
    
    public void update(Object object) {
        em.merge(object);
    }
}
